import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import {Button, Card, Checkbox, Col, Divider, Form, Input, Menu, Modal, Row, Tree,TreeSelect,} from 'antd';
import TableList from '@/components/TableList';
import SceenTable from '@/components/BindPerson/SceenTable';
import HasUser from '@/components/BindPerson/HasUser';
import HasGroup from '@/components/BindGroup/HasGroup';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';

const FormItem = Form.Item;
const {TreeNode} = Tree;
const CheckboxGroup = Checkbox.Group;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const CreateForm = Form.create(scene)(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    isDetail,
    text,
    detailsPageDate,
    arrayToString,
    arrayToArray,
    handleBindUserVisible,
    handleDitBoxVisible,
    handleBindOrgVisible,
    setHasList,
    hasList,
    groupMember,
    handleHasUserVisible,
    handleHasGroupVisible,
    levelOptions,
  } = props;


  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addDataFn(fieldsValue);
      }
    });
  };

  const userChange = (v) => {
    setHasList(v);
  }

  const whichBoxShow = (e) => {
    if (e == 0) {//人员弹框
      handleBindUserVisible(true, text);
    } else if (e == 1) { // 组织机构弹框

      handleBindOrgVisible(true, text)
    } else if (e == 2) {

//定义弹框
      handleDitBoxVisible(true, text)

    }
  }

  const removeByValue = (arr, val) => {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  }

  if (isDetail && detailsPageDate) {
    const {data} = detailsPageDate;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'userName',
      },
      {
        title: '登录名',
        dataIndex: 'userCode',

      },
      {
        title: '所属组织',
        dataIndex: 'organize',

      }
    ];
    return (
      <Modal
        destroyOnClose
        width={640}
        title="查看详情"
        visible={modalVisible}
        onOk={() => handleModalVisible()}
        onCancel={() => handleModalVisible()}
      >
        <SceenTable text={text} arrayToString={arrayToString} strategyTargetVoList={text.strategyTargetVoList}/>
      </Modal>
    )
  } else {
    //新增或者编辑
    const strategyFilelevelVoList = (JSON.stringify(text) != '{}' && text) ? arrayToArray(text.strategyFilelevelVoList, 'fileLevel') : [];
    const strategyOpttypeVoList = (JSON.stringify(text) != '{}' && text) ? arrayToArray(text.strategyOpttypeVoList, 'optType') : [];
    const strategyTargetVoList = (JSON.stringify(text) != '{}' && text) ? arrayToArray(text.strategyTargetVoList, 'userType') : [];

    // let list = form.getFieldValue('strategyTargetVoList')||[]
    // if(list&&groupMember&&groupMember.length==0&&list.indexOf(0)>-1) {
    //   list && list.length && removeByValue(list,0)
    //   form.setFieldsValue({
    //     strategyTargetVoList: list
    //   })
    // }else if(list&&groupMember&&groupMember.length&&list.indexOf(0)==-1) {
    //   list.push(0)
    //   form.setFieldsValue({
    //     strategyTargetVoList: list
    //   })
    // }

    return (
      <Modal
        destroyOnClose
        width={640}
        title={text ? '编辑操作黑名单' : '新增操作黑名单'}
        visible={modalVisible}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
        maskClosable={false}
      >
        <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="策略名称">
          {form.getFieldDecorator('name', {
            rules: [{required: true, message: '不能包含?*#等特殊字符'}], initialValue: text && text.name || ''
          })(<Input placeholder="请输入"/>)}
        </FormItem>
        <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="文件等级">
          {form.getFieldDecorator('strategyFilelevelVoList', {
            initialValue: strategyFilelevelVoList
          })(
            <CheckboxGroup options={levelOptions}/>
            // <CheckboxGroup>
            //   <Checkbox value={1}>非密</Checkbox>
            //   <Checkbox value={2}>秘密</Checkbox>
            //   <Checkbox value={3}>机密</Checkbox>
            //   <Checkbox value={4}>绝密</Checkbox>
            // </CheckboxGroup>
          )}
        </FormItem>
        <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="禁止操作">
          {form.getFieldDecorator('strategyOpttypeVoList', {
            initialValue: strategyOpttypeVoList
          })(<CheckboxGroup>
              <Checkbox value={0}>下载</Checkbox>
              <Checkbox value={1}>流转</Checkbox>
              <Checkbox value={2}>外发</Checkbox>
              <Checkbox value={3}>共享</Checkbox>
              <Checkbox value={4}>编辑</Checkbox>
            </CheckboxGroup>
          )}
        </FormItem>

        <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="操作对象">
          {form.getFieldDecorator('strategyTargetVoList', {
            initialValue: strategyTargetVoList
          })(<CheckboxGroup onChange={userChange}>
              <Checkbox value={0}/>
              <a onClick={() => whichBoxShow(0, text)} style={{cursor: 'pointer', marginLeft: 10}}>请选择人员</a>
              <a onClick={() => handleHasUserVisible(true)} style={{marginLeft: 25}}>查看</a>

              <br/>
              <Checkbox value={1}/>
              <a onClick={() => whichBoxShow(1, text)} style={{cursor: 'pointer', marginLeft: 10}}>请选择组织机构</a>


              <br/>
              <Checkbox value={2}/>
              <a onClick={() => whichBoxShow(2, text)} style={{cursor: 'pointer', marginLeft: 10}}>请选择自定义组</a>
              <a onClick={() => handleHasGroupVisible(true)} style={{marginLeft: 25}}>查看</a>


            </CheckboxGroup>
          )}
        </FormItem>
      </Modal>
    );
  }
})

/* eslint react/no-multi-comp:0 */
@connect(({scene, loading}) => ({
  scene,
  loading: loading.models.scene,
}))

@Form.create()

class scene extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    isDetail: false,
    detailsPageDate: {},
    text: {},
    bindUserVisible: false, //绑定用户
    treeDataList: [],//组织树
    orgDataList: {},//用户
    userInfo: {},
    ditBoxVisible: false, // 自定义弹框
    diyOrgData: {}, //diy自定义数据
    //增加和编辑的时候，需要各组组件之间传递用户信息（人员、组织机构、自定义组）
    groupMember: [],
    organizeData: [],
    customData: [],
    hasUserVisible: false,
    hasList: [],
    hasGroupVisible: false,
    levelOptions: [],
  };

  columns = [
    {
      title: '策略名称',
      dataIndex: 'name',
    },
    {
      title: '禁止操作',
      render: (text, record) => (
        <span>{this.arrayToString(text.strategyOpttypeVoList, 'optTypeName')}</span>
      ),
    },
    {
      title: '文件等级',
      render: (text, record) => (
        <span>{this.arrayToString(text.strategyFilelevelVoList, 'fileLevelName')}</span>
      ),

    },
    {
      title: '用户类型',
      render: (text, record) => (
        <span>{this.arrayToString(text.strategyTargetVoList, 'userTypeName')}</span>
      ),
    },
    {
      title: '操作',
      render: (text) => (
        <Fragment>
          <a onClick={() => this.openDetailsPage(true, text)}>详情</a>
          <Divider type="vertical"/>
          <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          <Divider type="vertical"/>
          <a onClick={() => this.deleteData(text.id)}>删除</a>
        </Fragment>
      ),
    },
  ];

  setHasList = (v) => {
    this.setState({
      hasList: v
    })
  }

  // 将数组对象的值转化为字符串显示
  arrayToString = (data = [], key) => {
    let str = '';
    data.map(function (v, i) {
      let newValue = v[key] ? v[key] : ' '
      if (data.length - 1 == i) {
        str = str + newValue;
      } else {
        str = str + newValue + ',';
      }
    });
    return str
  };

  //将数组对象的值重新放一个数组里
  arrayToArray = (data = [], key) => {
    const arr = [];
    data.map(function (v, i) {
      arr.push(v[key])
    });
    return arr
  };

  openDetailsPage = (flag, res) => {
    this.handleModalVisible(true, res);
    this.setState({
      isDetail: true
    });
  };

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  // 删除方法
  handleDeleteData(strategySituationIdList) {
    const {dispatch} = this.props;
    dispatch({
      type: 'scene/remove',
      payload: {strategySituationIdList},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.setState({selectedRows: []})
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  // 分页查询列表
  pageList(dataDict, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      name: dataDict && dataDict.dicName || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'scene/queryList',
      payload: values,
    });
  }

  // diy组织请求
  diyOrgTree(res, pageSize = 5, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      strategyId: res && res.strategyId || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'scene/diyOrgTree',
      payload: values,
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            diyOrgData: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  componentDidMount() {
    this.pageList();
    this.treeData(); // 组织树请求
    this.queryLevel();//查询敏感等级
    // this.diyOrgTree(); // diy组织请求
  }

  // 已选择自定义组详情弹框
  handleHasGroupVisible = (flag) => {
    this.setState({
      hasGroupVisible: !!flag,
    });
  };

  deleteGroup = (id) => {
    const {customData} = this.state;
    let copyGM = [...customData];
    copyGM.map((v, i) => {
      if (v.id == id) {
        copyGM.splice(i, 1);
      }
    })
    this.setState({
      customData: copyGM,
    })
  }

  // 已选择成员详情弹框
  handleHasUserVisible = (flag) => {
    this.setState({
      hasUserVisible: !!flag,
    });
  };

  deleteGMember = (userCode) => {
    const {groupMember} = this.state;
    let copyGM = [...groupMember];
    copyGM.map((v, i) => {
      if (v.userCode == userCode) {
        copyGM.splice(i, 1);
      }
    })
    this.setState({
      groupMember: copyGM,
    })
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);

    });
  };

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      isDetail: false,
      text: text,
      hasList: [],
    });
    if (flag) {
      this.diyOrgTree({strategyId: text && text.id || ''})
    }
    if (flag && text) {
      const strategyTargetVoList = text.strategyTargetVoList;
      let groupMember = [];
      let organizeData = [];
      let customData = [];
      strategyTargetVoList && strategyTargetVoList.length ? strategyTargetVoList.map((v) => {
        if (v.userTypeName == '人员') {
          groupMember = v.objectList;
        }
        if (v.userTypeName == '组织机构') {
          organizeData = v.userCodeList;
        }
        if (v.userTypeName == '自定义组') {
          customData = v.objectList;
        }
      }) : null;
      this.setState({
        groupMember,
        organizeData,
        customData,
      })
    }
    if (!flag) {
      this.setState({
        diyOrgData: {},
        groupMember: [],
        organizeData: [],
        customData: [],
      })
    }
  };

  // 更新接口
  updateFn = (fields, text) => {
    const {dispatch} = this.props;
    const {groupMember, organizeData, customData, hasList} = this.state;
    if (hasList.indexOf(0) > -1 && !groupMember.length) {
      Modal.warning({title: '操作失败', content: '请选择用户'});
      return
    }
    if (hasList.indexOf(1) > -1 && !organizeData.length) {
      Modal.warning({title: '操作失败', content: '请选择组织机构'});
      return
    }
    if (hasList.indexOf(2) > -1 && !customData.length) {
      Modal.warning({title: '操作失败', content: '请选择自定义组'});
      return
    }
    let objO = {};
    fields.strategyFilelevelVoList.map((v, i) => {
      let fileLevel = 'strategyFilelevelPoList[' + i + '].fileLevel';
      objO[fileLevel] = v;
    });

    let objT = {};
    fields.strategyOpttypeVoList.map((v, i) => {
      let optType = 'strategyOpttypePoList[' + i + '].optType';
      objT[optType] = v;
    });

    let objS = {};
    let newI = 0;
    fields.strategyTargetVoList.map((v, i) => {
      if (v == 0) {
        groupMember.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item.userCode;
          objS[userType] = 0;
          newI++;
        });
      } else if (v == 1) {
        organizeData.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item;
          objS[userType] = 1;//组织
          newI++;
        });
      } else {//v==2
        customData.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item.id;
          objS[userType] = 2;//自定义组
          newI++;
        });
      }
    });
    const params = {
      name: fields.name,
      id: text.id,
    }
    const assignObj = Object.assign(params, objO, objT, objS);
    dispatch({
      type: 'scene/update',
      payload: assignObj,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const {dispatch} = this.props;
    const {groupMember, organizeData, customData, hasList} = this.state;
    if (hasList.indexOf(0) > -1 && !groupMember.length) {
      Modal.warning({title: '操作失败', content: '请选择用户'});
      return
    }
    if (hasList.indexOf(1) > -1 && !organizeData.length) {
      Modal.warning({title: '操作失败', content: '请选择组织机构'});
      return
    }
    if (hasList.indexOf(2) > -1 && !customData.length) {
      Modal.warning({title: '操作失败', content: '请选择自定义组'});
      return
    }
    let objO = {};
    fields.strategyFilelevelVoList.map((v, i) => {
      let fileLevel = 'strategyFilelevelPoList[' + i + '].fileLevel';
      objO[fileLevel] = v;
    });

    let objT = {};
    fields.strategyOpttypeVoList.map((v, i) => {
      let optType = 'strategyOpttypePoList[' + i + '].optType';
      objT[optType] = v;
    });

    let objS = {};
    let newI = 0;
    fields.strategyTargetVoList.map((v, i) => {
      if (v == 0) {
        groupMember.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item.userCode;
          objS[userType] = 0;
          newI++;
        });
      } else if (v == 1) {
        organizeData.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item;
          objS[userType] = 1;//组织
          newI++;
        });
      } else {//v==2

        customData.map((item) => {
          let userCode = 'strategyTargetPoList[' + newI + '].userCode';
          let userType = 'strategyTargetPoList[' + newI + '].userType';
          objS[userCode] = item.id;
          objS[userType] = 2;//自定义组
          newI++;
        });

      }
    });
    const params = {
      name: fields.name,
    }
    const assignObj = Object.assign(params, objO, objT, objS);
    dispatch({
      type: 'scene/add',
      payload: assignObj,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.setState({
            groupMember: [],
            organizeData: [],
            customData: [],
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="策略名称">
              {getFieldDecorator('dicName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag, userInfo) => {
    this.setState({
      bindUserVisible: !!flag,
      userInfo: userInfo
    });
    if (!flag) {
      this.setState({
        orgDataList: {}
      })
    }
  };

  // 绑定用户弹框显示和隐藏
  handleDitBoxVisible = (flag, userInfo) => {
    this.setState({
      ditBoxVisible: !!flag,
      userInfo: userInfo
    });
  };

  // 绑定用户弹框显示和隐藏
  handleBindOrgVisible = (flag, userInfo) => {
    this.setState({
      bindOrgVisible: !!flag,
      userInfo: userInfo
    });
  };

  // 组织树请求
  queryLevel() {
    const {dispatch} = this.props;
    dispatch({
      type: 'scene/queryLevel',
      payload: {sensitiveState: 0},
      callback: (res) => {
        if (res.result == "ok") {
          let tempOptions = [];
          res.data.dataList.forEach(item => {
            tempOptions.push({label: item.name, value: item.sensitiveLevel});
          })

          this.setTempOptions(tempOptions);
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  setTempOptions = (options) => {
    this.setState({levelOptions: options});
  }

  // 组织树请求
  treeData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'scene/getTree',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            treeDataList: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //组织人员请求
  orgList(res, pageSize = 5, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      orgId: res && res.orgId,
      strategyId: res && res.strategyId || '',
      pageSize: pageSize,
      pageNum: pageNum,
      userName: res && res.userName || '',
      userCode: res && res.userCode || '',
    };
    dispatch({
      type: 'scene/getList',
      payload: values,
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            orgDataList: res.data,
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  setPeopleData(v) {
    const {groupMember} = this.state;
    const concatArr = v ? groupMember.concat(v) : groupMember;
    // 去重
    const result = [];
    let obj = {};
    for (var i = 0; i < concatArr.length; i++) {
      if (!obj[concatArr[i].userCode]) {
        result.push(concatArr[i]);
        obj[concatArr[i].userCode] = true;
      }
    }
    this.setState({
      groupMember: result,
    })
  }

  setOrganizeData(v) {
    this.setState({
      organizeData: v,
    })
  }

  setCustomData(v) {
    const {customData} = this.state;
    const concatArr = v ? customData.concat(v) : customData;
    // 去重
    const result = [];
    let obj = {};
    for (var i = 0; i < concatArr.length; i++) {
      if (!obj[concatArr[i].id]) {
        result.push(concatArr[i]);
        obj[concatArr[i].id] = true;
      }
    }
    this.setState({
      customData: result,
    })
  }

  render() {
    const {
      scene: {data},
      loading,
      form,
    } = this.props;

    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      isDetail,
      text,
      detailsPageDate,
      bindUserVisible,
      treeDataList,
      orgDataList,
      userInfo,
      ditBoxVisible,
      diyOrgData,
      bindOrgVisible,
      groupMember,
      organizeData,
      customData,
      hasList,
      hasUserVisible,
      hasGroupVisible,
      levelOptions,
    } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      isDetail: isDetail,
      detailsPageDate: this.state.detailsPageDate,
      arrayToString: this.arrayToString,
      arrayToArray: this.arrayToArray,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      handleBindUserVisible: this.handleBindUserVisible,
      handleDitBoxVisible: this.handleDitBoxVisible,
      handleBindOrgVisible: this.handleBindOrgVisible,
      setPeopleData: this.setPeopleData.bind(this),
      setHasList: this.setHasList,
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      handleHasGroupVisible: this.handleHasGroupVisible.bind(this),
    };

    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible,
      orgList: this.orgList.bind(this),
      setPeopleData: this.setPeopleData.bind(this),
    }

    const BindOrgMethods = {
      handleBindOrgVisible: this.handleBindOrgVisible,
      setOrganizeData: this.setOrganizeData.bind(this),
    }

    const BindDiyMethods = {
      handleDitBoxVisible: this.handleDitBoxVisible,
      diyOrgTree: this.diyOrgTree.bind(this),
      setCustomData: this.setCustomData.bind(this)
    }

    const hasUserMethods = {
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      deleteGMember: this.deleteGMember.bind(this),
    }

    const hasGroupMethods = {
      handleHasGroupVisible: this.handleHasGroupVisible.bind(this),
      deleteGroup: this.deleteGroup.bind(this),
    }

    return (
      <PageHeaderWrapper title="场景策略">
        <Card bordered={false}>
          {modalVisible ? <CreateForm
            {...parentMethods}
            modalVisible={modalVisible}
            text={text}
            hasList={hasList}
            levelOptions={levelOptions}
            groupMember={groupMember}
          /> : null}
          {hasGroupVisible ? <HasGroup
            {...hasGroupMethods}
            hasGroupVisible={hasGroupVisible}
            customData={customData}
          /> : null}
          {hasUserVisible ? <HasUser
            {...hasUserMethods}
            hasUserVisible={hasUserVisible}
            groupMember={groupMember}
          /> : null}
          {bindUserVisible ? <TreeList
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            orgDataList={orgDataList}
            form={form}
            userInfo={userInfo}
            groupMember={groupMember}
          /> : null}
          {bindOrgVisible ? <OrgListBox
            {...BindOrgMethods}
            bindOrgVisible={bindOrgVisible}
            treeDataList={treeDataList}
            organizeData={organizeData}
            userInfo={userInfo}
          /> : null}
          {ditBoxVisible ? <DiyOrgBox
            {...BindDiyMethods}
            ditBoxVisible={ditBoxVisible}
            diyOrgData={diyOrgData}
            customData={customData}
            userInfo={userInfo}
          />:null}

          <div className={styles.tableList}>
            {
              <div className={styles.tableListForm}>{this.renderForm()}</div>
            }
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

// 增加用户弹框
class TreeList extends PureComponent {
  state = {
    selectedRows: [],
    orgId: '',//树节点ID
    strategyId: '',
    selectedRowKeys: [], // 勾选几项，下次默认进来勾选
  };
  okHandle = () => {
    const {form, handleBindUserVisible, setPeopleData} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      const {selectedRows, strategyId} = this.state;
      setPeopleData(selectedRows);
      handleBindUserVisible();
    });

  };

  handleUserList = (pagination) => {
    const {userInfo} = this.props;
    const {orgId} = this.state;
    const strategyId = userInfo && userInfo.id || '';
    this.props.orgList({orgId, strategyId}, pagination.pageSize, pagination.current - 1);
  }

  componentDidMount() {
    const {treeDataList, userInfo} = this.props;
    const strategyId = userInfo && userInfo.id || '';
    this.props.orgList({orgId: treeDataList&&treeDataList[0].id, strategyId});
  }

  onSelect = (info) => {
    const {userInfo} = this.props;
    const orgId = info[0];
    const strategyId = userInfo && userInfo.id || '';
    this.props.orgList({orgId, strategyId});
    this.setState({
      orgId,
      strategyId: orgId,
    })
  }

  handleSelectRowsNew = (selectedRows) => {
    this.setState({
      selectedRows: selectedRows,
    });
  };

  render() {
    const {bindUserVisible, handleBindUserVisible, treeDataList, orgDataList} = this.props;
    const {selectedRows, selectedRowKeys} = this.state;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'userName',

      },
      {
        title: '登录名',
        dataIndex: 'userCode',
      }
    ];
    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}>
            {loop(item.children || [])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });

    return (
      <Modal
        destroyOnClose
        width={1000}
        title='选择人员'
        visible={bindUserVisible}
        onOk={this.okHandle}
        onCancel={() => handleBindUserVisible()}
        bodyStyle={{padding: '0'}}
        maskClosable={false}
      >
        {/*defaultExpandedKeys={['1']}*/}

        <GridContent className={styles.userCenter}>
          <Row gutter={8}>
            <Col lg={7} md={24}>
              <Card bordered={false}>
              <div className={styles.modalTreeScroll}>
                {treeDataList && treeDataList.length ? <Tree
                  showLine={true}

                  onSelect={this.onSelect}
                >
                  {loop(treeDataList || [])}
                </Tree> : null}
                </div>
              </Card>
            </Col>
            {
              <Col lg={17} md={24}>
                <Card bordered={false} bodyStyle={{padding: '24px 24px 24px 0'}}>
                  <TableList
                    className={styles.tdPadding}
                    selectedRows={selectedRows}
                    loading={false}
                    data={orgDataList}
                    columns={columns}
                    onSelectRow={this.handleSelectRowsNew}
                    onChange={this.handleUserList}
                    rowKey={record => record.userId}
                  />
                </Card>
              </Col>
            }
          </Row>
        </GridContent>
      </Modal>
    );
  }
}

// 组织机构弹框
class OrgListBox extends PureComponent {
  state = {
    organizeData: [],
    defalutKey: [''],
  };
  okHandle = () => {
    const {setOrganizeData, handleBindOrgVisible} = this.props;
    const {organizeData} = this.state;
    setOrganizeData(organizeData);
    handleBindOrgVisible();
  };

  onCheck = (info, e) => {
    this.setState({
      organizeData: info,
    })
  }

  componentDidMount() {
    const {userInfo, organizeData} = this.props;
    this.setState({defalutKey: organizeData})
  }

  render() {
    const {bindOrgVisible, handleBindOrgVisible, treeDataList} = this.props;
    const {defalutKey} = this.state;
    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}   showCheckedStrategy={TreeSelect.SHOW_PARENT}>
            {loop(item.children || [])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });

    return (
      <Modal
        destroyOnClose
        width={800}
        title='选择组织'
        visible={bindOrgVisible}
        onOk={this.okHandle}
        onCancel={() => handleBindOrgVisible()}
      >
       <div className={styles.modalTreeScroll}>
        {treeDataList && treeDataList.length ? <Tree
          checkable
          defaultCheckedKeys={defalutKey}
          showCheckedStrategy={TreeSelect.SHOW_PARENT}
          treeCheckable={true}
          multiple={false}
          defaultExpandedKeys={defalutKey && defalutKey.length ? defalutKey : [treeDataList[0].id.toString()]}
          showLine={true}
          onCheck={this.onCheck}
        >
          {loop(treeDataList || [])}
        </Tree> : null}
        </div>
      </Modal>
    );
  }
}

// 自定义组织弹框
class DiyOrgBox extends PureComponent {
  state = {
    selectedRows: []
  };
  okHandle = () => {
    const {form, setCustomData, handleDitBoxVisible} = this.props;
    const {selectedRows} = this.state;
    setCustomData(selectedRows);
    handleDitBoxVisible();
  };

  handleDIYList = (pagination) => {
    const {userInfo} = this.props;
    this.props.diyOrgTree({strategyId: userInfo && userInfo.id || ''}, pagination.pageSize, pagination.current - 1);
  }

  handleSelectRowsNew = (selectedRows) => {
    this.setState({
      selectedRows: selectedRows,
    });
  };

  render() {
    const {ditBoxVisible, handleDitBoxVisible, diyOrgData, userInfo} = this.props;
    const {selectedRows} = this.state;
    const columns = [
      {
        title: '自定义组名',
        dataIndex: 'groupName',

      },
      {
        title: '自定义组管理员',
        dataIndex: 'adminUserName',
      }
    ];

    return (
      <Modal
        destroyOnClose
        width={800}
        title='选择自定义组'
        visible={ditBoxVisible}
        onOk={this.okHandle}
        onCancel={() => handleDitBoxVisible()}
      >
        <TableList
          className={styles.tdPadding}
          selectedRows={selectedRows}
          loading={false}
          data={diyOrgData}
          columns={columns}
          onSelectRow={this.handleSelectRowsNew}
          onChange={this.handleDIYList.bind(this)}
          rowKey={record => record.id}
        />
      </Modal>
    );
  }
}

export default scene;
